// This file is part of OpenTSDB.
// Copyright (C) 2017 TeleDB Development Group.
//
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 2.1 of the License, or (at your
// option) any later version.  This program is distributed in the hope that it
// will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser
// General Public License for more details.  You should have received a copy
// of the GNU Lesser General Public License along with this program.  If not,
// see <http://www.gnu.org/licenses/>.
package net.opentsdb.tsd.controller;

import com.google.common.base.Joiner;
import com.google.common.collect.Sets;
import net.opentsdb.core.TSDB;
import net.opentsdb.utils.hbase.HbaseWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;
import java.util.Set;

public class RemoveTagsController {
    private static final Logger LOG = LoggerFactory.getLogger(RemoveTagsController.class);

    private final TSDB tsdb;
    private final String metric;
    private final HbaseWrapper wrapper;

    public RemoveTagsController(TSDB tsdb, String metric){
        this.tsdb = tsdb;
        this.metric = metric;
        wrapper = tsdb.getHbaseWrapper();
    }

    public void handle() throws Exception{
        for(String delTagk : getDelTagks()){
            wrapper.tagUtils.deleteTagTree(metric, delTagk);
        }

        tsdb.getClient().flush().joinUninterruptibly();

        if(!wrapper.tagUtils.existsTagsTagkData(metric.getBytes(StandardCharsets.UTF_8)))
            wrapper.tagUtils.deleteTagTree(metric);
    }

    private Set<String> getDelTagks(){
        Set<String> targetTagks = wrapper.tagUtils.fetchTagsTagks(metric);
        Set<String> sourceTagks = wrapper.metaUtils.fetchMetricAllTagk(tsdb, metric);
        Set<String> delTagks = Sets.newHashSet();

        // 取tag和meta所有tagk的差集
        for(String tagk : targetTagks){
            if(!sourceTagks.contains(tagk))
                delTagks.add(tagk);
        }
        LOG.debug("metric {} tagk {} tsuid is empty, so clear tag table data",
                metric,Joiner.on(",").join(delTagks));

        return delTagks;
    }
}
